package org.liushengpei.com.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.liushengpei.com.domain.GoodsInfo;
import org.liushengpei.com.domain.esdomain.GoodsImgIndex;
import org.liushengpei.com.domain.esdomain.GoodsInfoIndex;
import org.liushengpei.com.domain.vo.GoodsInfoVO;
import org.liushengpei.com.mapper.GoodsInfoMapper;
import org.liushengpei.com.repository.GoodsInfoRepository;
import org.liushengpei.com.service.IGoodsInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 商品信息逻辑控制实现类
 */
@Service
public class GoodsInfoServiceImpl extends ServiceImpl<GoodsInfoMapper, GoodsInfo> implements IGoodsInfoService {

    @Autowired
    private GoodsInfoRepository repository;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    /**
     * 商品详情信息id
     */
    private static final String GOODSINFOID = "goodsInfoId";

    /**
     * 删除标识
     */
    private static final String DELFLAG = "delFlag";

    /**
     * 获取商品详细信息
     *
     * @param id 商品id
     */
    @Override
    public GoodsInfoVO getGoodsInfoById(String id) {
        GoodsInfoVO infoVO = new GoodsInfoVO();
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //查询商品信息
        Optional<GoodsInfoIndex> goodsInfo = repository.findById(Long.valueOf(id));
        if (goodsInfo.isPresent()) {
            GoodsInfoIndex goodsInfoIndex = goodsInfo.get();
            infoVO.setGoodsInfoIndex(goodsInfoIndex);
            //查询商品的介绍图片地址
            List<String> imageList = new ArrayList<>();
            //构建查询条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery(GOODSINFOID, goodsInfoIndex.getId()));
            boolQueryBuilder.filter(QueryBuilders.termQuery(DELFLAG, 0));
            queryBuilder.withQuery(boolQueryBuilder);
            SearchHits<GoodsImgIndex> searchHits = restTemplate.search(queryBuilder.build(), GoodsImgIndex.class);
            for (SearchHit<GoodsImgIndex> searchHit : searchHits) {
                //获取结果
                GoodsImgIndex goodsImg = searchHit.getContent();
                imageList.add(goodsImg.getImageUrl());
            }
            infoVO.setGoodsImgsList(imageList);
        }
        return infoVO;
    }
}
